<template>
  <view class="content">
    <view class="notice">
      <view class="notice-box">
        <image
          src="@/static/team/shopkeeper/notice.png"
          mode="widthFix"
        ></image>
        <view class="notice-text"
          >商品赠送，为A的云仓库存免费赠送给B的云仓，仅为库存转移，不生成订单，不计算奖励，赠送后不可撤回，请谨慎操作。</view
        >
      </view>
    </view>

    <view class="goods">
      <view class="goods-shore">
        <text>商品赠送</text>
        <text :class="giftgoorderData.length > 0 ? 'gh-shore' : 'gh-no-shore'"
          >已选:{{ numfun() }}</text
        >
      </view>
      <view v-if="giftgoorderData.length > 0">
        <view
          class="goods-info"
          v-for="(item, index) in giftgoorderData"
          :key="index"
        >
          <view class="goods-info-img">
            <image :src="item.product.image" mode="scaleToFill" />
          </view>
          <view class="goods-info-detail">
            <view class="goods-info-detail-name">
              <view class="goods-name">{{ item.product.store_name }}</view>
              <view class="goods-dec">默认</view>
            </view>
            <view class="goods-priceornum">
              <view class="goods-price"
                ><text> ¥{{ formatPrice(item.product.price) }}</text></view
              >
              <view class="goods-num">
                <up-number-box
                  integer
                  :min="0"
                  :max="item.quantity"
                  bgColor="#ffffff"
                  v-model="item.product_num"
                ></up-number-box>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="goods-paylist" v-if="giftgoorderData.length > 0">
        <view class="goods-paylist-item">
          <view class="selectProduct" @click="selectProduct">
            <image src="@/static/cloudlibrary/add-img.png" mode="widthFix" />
            <!-- <image src="../static/add-img2.png" mode="widthFix" /> -->
            选择商品</view
          >
        </view>
      </view>
      <view class="goods-paylist" v-else>
        <view class="goods-paylist-item">
          <view class="selectProduct noProduct" @click="selectProduct">
            <image src="@/static/cloudlibrary/add-img2.png" mode="widthFix" />
            选择商品</view
          >
        </view>
      </view>
    </view>

    <view class="content-phone">
      <view class="content-phone-title"> 手机号查找受赠方 </view>
      <view class="content-phone-input">
        <up-input placeholder="输入对方手机号，赠送商品" v-model="keywords">
          <template #suffix>
            <view
              :class="keywords ? 'pay-cx-bt1' : 'pay-cx-bt'"
              size="mini"
              @click="phoneSearch"
              >查询</view
            >
          </template>
        </up-input>
      </view>
    </view>

    <view class="footer-card" v-if="cardData">
      <view class="user-card-img">
        <image :src="cardData.avatar" mode="widthFix"></image>
      </view>
      <view
        class="user-card-identity"
        :class="
          cardData.level_id == 101
            ? 'user-card-identity'
            : cardData.level_id == 201
            ? 'shopkeeper'
            : cardData.level_id == 301
            ? 'distributor'
            : cardData.level_id == 401
            ? 'serviceCentre'
            : cardData.level_id == 501
            ? 'serviceCentre'
            : ''
        "
        >{{ cardData.level_name }}</view
      >
      <view class="user-card-name">{{ cardData.nickname }}</view>

      <view class="user-card-info">
        <view class="info-id">ID：{{ cardData.uid }}</view>
        <view class="info-phone">手机号：{{ cardData.phone }}</view>
      </view>
    </view>

    <view class="foodr-bt">
      <view
        :class="giftgoorderData.length > 0 ? 'bt-sbuit' : 'bt-sbuit bt-color'"
        @click="productGift"
        >赠送商品</view
      >
    </view>

    <!-- 赠送商品弹框 -->
    <u-popup
      :show="showPopup"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">温馨提示</view>
        <view class="popup-content-item"
          >商品免费赠送无法撤回，请确认赠送给<text
            >“{{ cardData.nickname }}{{ cardData.phone }}”</text
          >开通？</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closepopup">取消</view>
            <view class="popup-content-cl" @click="gopassword">确定赠送</view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 密码弹框 -->
    <view class="password_show">
      <u-popup
        :show="showPassword"
        mode="center"
        round="10"
        @close="close"
        @open="open"
      >
        <view class="password">
          <view class="popup-content-title">支付密码</view>
          <u-code-input
            v-model="pay_pass"
            :maxlength="6"
            dot
            size="80"
            @change="onChange"
            @finish="finish"
            :focus="focusinput"
          ></u-code-input>
          <view class="footer">
            <view class="closefun" @click="showPassword = false">取消</view>
            <view class="forgot" @click="forgot">忘记密码？</view>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script setup>
import { inject, ref } from "vue";
import { giveApi, giveUserQuestApi } from "@/services/cloudlibrary";
import { onLoad, onShow } from "@dcloudio/uni-app";

import { selectgiftProductStore } from "@/stores/selectgiftProduct";
import { mine, isPayPassApi, checkPayPass } from "@/services/user";
import { formatPrice } from "@/utils/formatPrice";

const selectgiftProductData = selectgiftProductStore();

onShow(() => {
  if (selectgiftProductData.selectgiftProduct) {
    giftgoorderData.value = selectgiftProductData.selectgiftProduct;
  }
  isPayPassFun();
});

// 搜索  手机号查询
const keywords = ref("");
const cardData = ref("");
const giftgoorderData = ref([]);

const phoneSearch = async () => {
  if (keywords.value.length != 11) {
    uni.showToast({
      title: "手机号码格式不正确!",
      icon: "none",
    });
    return;
  }
  try {
    // 发送请求
    let res = await giveUserQuestApi({ phone: keywords.value });
    cardData.value = res.data;
  } catch (e) {
    if (e.info == "用户不存在") {
      uni.showToast({
        title: "您不是他的推荐人，无法赠送",
        icon: "none",
      });
    } else {
      uni.$u.toast(e.info);
    }
    // uni.showToast({
    //   title: "您不是他的推荐人，无法查询",
    //   icon: "none",
    // });
    cardData.value = "";
  }
};

const selectProduct = () => {
  uni.navigateTo({
    url: "/pages/cloudlibrary/giftgood/index",
  });

  // selectProductData.setselectProduct(giftgoorderData.value);
  // uni.reLaunch({
  //   url: "/pages/cloudlibrary/giftgood/index",
  // });
};

// 赠送商品
const showPopup = ref(false);
const productGiftData = ref({});

const productGift = () => {
  if (productGiftData.value && numfun() > 0 && cardData.value) {
    if (cardData.value.level_id == 101) {
      uni.showToast({
        title: "对方为会员身份，无云仓权限，无法赠送!",
        icon: "none",
      });
      return;
    } else {
      showPopup.value = true;
    }
  } else {
    uni.showToast({
      title: "请选择商品和受赠人",
      icon: "none",
    });
  }
};
const closepopup = () => {
  showPopup.value = false;
};

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showPassword = ref(false);
const gopassword = () => {
  if (isPayPass.value != 0) {
    showPassword.value = true;
    pay_pass.value = "";
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else {
    uni.showToast({
      title: "没有支付密码，前往设置",
      icon: "none",
    });
    setTimeout(() => {
      uni.navigateTo({
        url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
      });
    }, 500);
  }
};
const pay_pass = ref("");
const gocancle = () => {
  showPassword.value = false;
  pay_pass.value = "";
};
// 赠送商品-确认按钮
const cartData = ref([]);
const ispay = ref(false);
const gepaymentfun = async () => {
  giftgoorderData.value.forEach((item, index) => {
    if (item.product_num > 0) {
      cartData.value.push(item);
    }
  });

  productGiftData.value = {
    product: cartData.value,
    recipient_id: cardData.value.uid,
    pay_pass: pay_pass.value,
  };
  try {
    // 防止小程序输入密码重复支付
    if (!ispay.value) {
      ispay.value = true;
    } else {
      return;
    }
    // 发送请求
    let res = await giveApi(productGiftData.value);
    if (res.code == 200) {
      uni.showToast({
        title: res.info,
        icon: "success",
      });
      selectgiftProductData.setselectgiftProduct([]);
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: "/pages/cloudlibrary/giftgood/index",
      //   });
      // }, 1000);
      setTimeout(() => {
        uni.redirectTo({
          url: "/pages/cloudlibrary/giftgood/index",
        });
      }, 1000);
    }
  } catch (e) {
    selectgiftProductData.setselectgiftProduct([]);
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

//计算商品总数
function numfun() {
  let num = 0;
  if (giftgoorderData.value.length > 0) {
    giftgoorderData.value.forEach((element, index) => {
      if (element.selectStatus) {
        num += element.product_num;
      }
    });
    return num;
  } else {
    return num;
  }
}

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      gepaymentfun();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + isPayPass.value,
  });
};

const close = () => {
  showPopup.value = false;
  showPassword.value = false;
  focusinput.value = false;
  pay_pass.value = "";
};

const focusinput = ref(false);
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
